Home | | Latest | About | Random
# Week 6 Friday
Dear Class,
Today we discuss the idea of function overloading (section 14). Please also start reviewing for the midterm exam! New stuff from sections 9 to 14 (inclusive), and up to and including HW4. You will also need to remember the old stuff! Add to your laundry list! You can do it!
-- B.
.
.
.
.
.
## Function overloading.
In C++, it is possible to reuse the same function name to perform different definitions, called **overloads**, based on the *parameter list*. This is called **function overloading**.
For example.
```cpp
#include
using namespace std;
void f(int x) { cout << "overload 1"; }
void f(int x, int y) { cout << "overload 2"; }
void f(bool x) { cout << "overload 3"; }
void f(double x) { cout << "overload 4"; }
int main () {
f(3); cout << endl;
f(6, 7); cout << endl;
f(true); cout << endl;
f(3.); cout << endl;
return 0;
}
```
Try it and see which overload gets called.
**In simple terms, the overload whose parameters match the arguments most closely is the one that is called.**
With the same `f` as above, which overload do you think gets called? Make your best guess first:
```cpp
f(0)
f(0.)
f(3.14, 3.14)
f('x')
```
We will explain this a bit more later.
We can also intuitively deduce which overload it chooses by what matches the parameter type the closest:
```cpp
#include
#include
using namespace std;
int f(string& s) { return 111; }
int f(const string& s) { return 222; }
int main() {
string s = "Hello";
const string cs = "Const";
cout << f(s) << endl;
cout << f(cs) << endl;
return 0;
}
```
Can you predict the output above?
**Note.** It is possible to have overloads with **different** return types, provided the parameter list is **different**, like the following
```cpp
int f(int x, double y) { return 1; }
double f(double x, int y) { return 2.2; }
bool f(int x, int y) { return true; }
char f(int x, int y, int z) { return 'A'; }
```
It is the order of the parameters and the type of the parameters that matters, but not the parameter name.
However, it is still a build error if the overloads have exactly the same parameter list but different return type:
```cpp
int f(int x, double y) { return 1; }
double f(int x, double y) { return 2.2; }
```
or
```cpp
int f(int x, double y) { return 1; }
double f(int y, double x) { return 2.2; }
```
The reason for a build error above is if you feed in arguments that are an `int`, followed by a `double`, it does not know which overload of `f` to choose!
.
.
.
.
.
## Why might one want to overload their functions
It is often the case where you want to perform similar actions but to different types of arguments, or you want to add some optional input to change how your function behaves. Here let's check out two examples
### Example 1. Print.
Perhaps we write a function that can print various different data types, like `int`, `string`, and `vector`. So we can write something like this
```cpp
#include
#include
#include
using namespace std;
void print(int x) { cout << x << endl;}
void print(const string& s) {cout << s << endl;}
void print(const vector& v) {
for(size_t i = 0; i < v.size(); ++i) {
cout << v.at(i) << ", ";
}
cout << endl;
}
int main() {
int i = 100;
string s = "Hello darkness my old friend";
vector v {1, 2, 3, 4};
print(i);
print(s);
print(v);
return 0;
}
```
### Example 2. Remove tail entries.
Recall for a `vector v`, we can add to the end of the `vector` `v` by doing `v.push_back(x)`, and remove the last entry by `v.pop_back()`. Let us write a function with an overload that removes the last entry when called, but one can also specify how many entries to remove from the end. Since `pop_back()` on an empty vector is actually undefined behavior, we can even add a guard here.
```cpp
void remove(vector& v);
void remove(vector& v, size_t n);
void remove(vector& v) {
if(v.empty()) { return;}
v.pop_back();
}
void remove(vector& v, size_t n) {
for(size_t i = 0; i < n; ++i) {
if(v.empty()) { return;}
v.pop_back();
}
}
```
.
.
.
.
.
## Resolving overload when implicit casting is involved.
A function call will attempt to perform implicit casting sometimes:
```cpp
#include
using namespace std;
int f(int x) { return x + 1; }
int main() {
cout << f(3) << endl;
cout << f(3.14) << endl;
return 0;
}
```
With overloading, one can make it pick the right overload to perform
```cpp
#include
using namespace std;
int f(int x) { return x + 1; }
int f(double x) { return x - 1; } // the return type int will also cast
int main() {
cout << f(3) << endl;
cout << f(3.14) << endl;
return 0;
}
```
But sometimes it gets ambiguous. For example the `bool b = true` can be casted into both `int` and `double`. But which one does it choose?
```cpp
#include
using namespace std;
int f(int x) { return x + 1; }
int f(double x) { return x - 1; } // the return type int will also cast
int main() {
bool b = true;
cout << f(b) << endl;
return 0;
}
```
Perhaps one could guess that `bool` is "closer" to `int`, so it picks `int`. And that's not too far off.
Note, if there is no overloading, each version of `f` would take `b` as an argument by implicitly casting! Try commenting out each overload one at a time.
But the situation gets even more confusing when we have something like this:
```cpp
#include
using namespace std;
int f(int x, int y) {return 111;}
int f(double x, double y) {return 222;}
int main() {
int i = 1;
double d = 1.1;
cout << f(i, i) << endl;
cout << f(d, d) << endl;
cout << f(i, d) << endl;
cout << f(d, i) << endl;
}
```
Which lines do you think would be ambiguous?
To determine this, let's play a game of **overload battle**. Imagine you have two lists of soldiers, consisting of **elites (E)**, **paladins (P)**, and **commoners (C)**. The two lists of soldiers go head to head, entry by entry in order, with the following rule:
- E beats P and C;
- P beats C.
- If the soldiers are of the same kind, then they tie.
![[1-teaching/ucla-2026-fall-pic-10a/---files/Week-6-Friday 2026-11-06 09.39.10.excalidraw.svg]]
%%[[1-teaching/ucla-2026-fall-pic-10a/---files/Week-6-Friday 2026-11-06 09.39.10.excalidraw.md|π Edit in Excalidraw]]%%
A list of soldiers is **the unambiguous winner if (1) it never loses a battle, (2) it wins at least one battle.**
Example
```
β β β
E P P P P P winner
P P P C P C
```
Example
```
E E P P E C
E E P E E C winner
β
```
Example
```
β β β β β
E C E E E E ambiguous!
P E C C C C ambiguous!
β
```
We do not care about how many wins, nor the quality of the wins.
Example
```
E P C ambiguous!
E P C ambiguous!
```
Complete tie is ambiguous.
Example: More than two lists
```
A: E P beats B and C, so winner
B: P C
C: C P (B vs C is a standoff, but irrelevant)
```
Here there is an absolute winner, which is `A`, since if we battle `A` with `B`, we have
```
β β
A: E P winner
B: P C
```
and battle `A` with `C`, we have
```
β
A: E P winner
C: C P
```
Ok, so what does this have to do with function overloading when there's implicit casting?
When an argument of type `A` is passed to a parameter of type `T` (written `A -> T`), with `A` and `T` among `int`, `double`, `bool` and `char`, every pairing is allowed, and each is one of:
- **Exact match (E):** `T -> T`.
- **Promotion (P):** only `bool -> int` and `char -> int`. (Also `float -> double`, but we rarely use `float`.)
- **Conversion (C):** every other pairing.
And now to determine which overload to pick, play the overload game above!
- **Compare parameter by parameter. Exact (E) beats promotion (P) and conversion (C). Promotion (P) beats conversion (C).**
- **A winner has to be an unambiguous winner: (1) never loses, and (2) wins at least one.**
- The quantity or quality of wins does not matter.
It it cannot be resolved according to above, we get a **build error** for **ambiguous overload**.
**Example.** Can you determine which line gives build error for ambiguous overloads? Comment out the lines with errors. What is the output of the rest?
```cpp
#include
using namespace std;
int h(int a, double b, double c) { return 111; }
int h(bool a, int b, double c) { return 555; }
int h(int a, int b, int c) { return 999; }
int main() {
int i = 1;
double d = 1.1;
char c = 'a';
bool b = true;
cout << h(b, c, b) << endl;
cout << h(i, c, b) << endl;
cout << h(b, c, d) << endl;
cout << h(d, c, b) << endl;
cout << h(d, d, i) << endl;
cout << h(c, d, d) << endl;
return 0;
}
```
**Example.** Repeat as above.
```cpp
#include
using namespace std;
int h(int a, double b, double c) { return 111; }
int h(int a, int b, double c) { return 999; }
int main() {
cout << h(1.1, 1.1, 1.1) << endl;
cout << h(1.1, 1.1, 1 ) << endl;
cout << h(1.1, 1 , 1.1) << endl;
cout << h(1.1, 1 , 1 ) << endl;
cout << h(1 , 1.1, 1.1) << endl;
cout << h(1 , 1.1, 1 ) << endl;
cout << h(1 , 1 , 1.1) << endl;
cout << h(1 , 1 , 1 ) << endl;
return 0;
}
```
**Example.** Repeat as above.
```cpp
#include
using namespace std;
int h(int a, double b, int c ) { return 111; }
int h(int a, int b, double c) { return 999; }
int main() {
cout << h(1.1, 1.1, 1.1) << endl;
cout << h(1.1, 1.1, 1 ) << endl;
cout << h(1.1, 1 , 1.1) << endl;
cout << h(1.1, 1 , 1 ) << endl;
cout << h(1 , 1.1, 1.1) << endl;
cout << h(1 , 1.1, 1 ) << endl;
cout << h(1 , 1 , 1.1) << endl;
cout << h(1 , 1 , 1 ) << endl;
return 0;
}
```
.
.
.
.
.
## Cases with passing in by value, by reference, and by reference to const.
When C++ chooses an overload, references add no extra cost. So passing a variable of type `T` to a `T` parameter or a `T&` parameter is an exact match both times, and the call is ambiguous.
Between `T&` and `const T&`, a non-const `T` argument prefers `T&`. A `const T` argument canβt bind to `T&` at all, so only the parameter `const T&` is viable.
**Practice.**
Predict the output here, if there is an error on a line, comment that line out and explain.
```cpp
#include
#include
using namespace std;
int f(string s) { return 1; }
int f(string& s) { return 2; }
int main() {
string s = "Hello";
const string cs = "Const";
cout << f(s) << endl;
cout << f(cs) << endl;
return 0;
}
```
**Practice.**
Predict the output here, if there is an error on a line, comment that line out and explain.
```cpp
#include
#include
using namespace std;
int f(string s) { return 1; }
int g(string& s) { return 222; }
int g(const string& s) { return 333; }
int main() {
string s = "Hello";
const string cs = "Const";
cout << f(s) << endl;
cout << f(cs) << endl;
cout << g(s) << endl;
cout << g(cs) << endl;
return 0;
}
```